package org.lazycoder.logger;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Vector;

import org.lazycoder.database.Table;

/**
 * Generates a simple report. This class is truly awful so don't use it. EVER!
 * 
 * @author Matthew Bayliss
 * 
 */
public class Reporter implements Runnable {

	Date date = new Date();
	private SimpleDateFormat format;
	private File directory;

	@Override
	public void run() {
		System.out.println("Creating report.");
		createReport();
		System.out.println("Done.");
	}

	private void createReport() {
		try {
			format = new SimpleDateFormat("y-M-d-H-m-s-S-z");
			String path = EventLogger.getInstance().getPath();
			directory = new File(path + "/reports/" + format.format(date));
			if (!directory.isDirectory()) {
				directory.mkdirs();
			}
			BufferedWriter writer = new BufferedWriter(new FileWriter(
					directory.getAbsolutePath() + "/report.html"));
			System.out.println(directory.getAbsolutePath());
			writer.write("<html>\n<head>\n<title>EventLogger Report - "
					+ format.format(date) + "</title>\n</head>\n<body>\n\t");
			Table table = EventLogger.getInstance().getEvents();
			Iterator<Vector<String>> ritr = table.getRowIterator();
			writer.write("<table>\n");

			//TODO Fix
			//Iterator<String> hitr = table.getHeaderRow().iterator();
			//writer.write("\t\t<tr>");
			//while (hitr.hasNext()) {
			//	writer.write("<th>" + hitr.next() + "</th>");
			//}
			writer.write("<th>Attachments</th>");
			writer.write("</tr>\n");

			while (ritr.hasNext()) {
				writer.write("\t\t<tr>");
				Iterator<String> citr = ritr.next().iterator();
				int i = 0, id = 0;
				while (citr.hasNext()) {
					String value = citr.next();
					if (i == 0) {
						id = Integer.valueOf(value);
					}
					writer.write("<td>" + value + "</td>");
					i++;
				}

				Vector<File> files = EventLogger.getInstance().getAttachments(
						id);
				Iterator<File> fitr = files.iterator();
				while (fitr.hasNext()) {
					writer.write("<td>");
					File file = fitr.next();
					File newFile = new File(directory.getAbsolutePath()
							+ "/atts/" + file.getName());
					newFile.mkdirs();
					Files.move(file.toPath(), newFile.toPath(),
							StandardCopyOption.REPLACE_EXISTING);
					writer.write(" <a href='" + newFile.getAbsolutePath()
							+ "'>Att</a> ");
					writer.write("</td>");
				}

				writer.write("</tr>\n");

			}
			writer.write("\t</table>\n</body>\n</html>");
			writer.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
